<?php

namespace App\Http\Controllers\Attribute;

use App\Models\Attribute;
use App\Models\AttributeClassify;
use App\Models\Classify;
use foo\bar;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AttributeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $attrs=Attribute::where('pid',0)->get();
        return view('attribute.attribute.index',compact('attrs'));
    }
   
    public function create()
    {
        $attrs=Attribute::where('pid',0)->get();
        return view('attribute.attribute.create',compact('attrs'));
    }
    public function store(Request $request)
    {
        $request->validate([
            'name'=>'required|unique:attributes',
        ],[
          'name.required'=>'属性名不能为空',
          'name.unique'=>'属性名不能重复',
        ]);
        Attribute::create($request->all());
        return back();
//        return redirect()->route('attribute.attribute.index')->with('success','添加属性成功');
    }
    public function show(Attribute $attribute)
    {
        //
    }
    public function edit(Attribute $attribute)
    {
        $attrs=Attribute::where('pid',0)->get();
        return view('attribute.attribute.edit',compact('attribute','attrs'));
    }

    public function update(Request $request, Attribute $attribute)
    {
        $request->validate([
            'name'=>'required|unique:attributes',
        ],[
            'name.required'=>'属性名不能为空',
            'name.unique'=>'属性名不能重复'
        ]);
        $attribute->update($request->all());
        return redirect()->route('attribute.attribute.index')->with('success','编辑成功');
    }
    public function destroy(Attribute $attribute)
    {
        
        $attribute->delete();
        return back()->with('success','删除成功');
    }
    //根据三级分类的id找其对应的属性
    public function attributeSon(Classify $classify){
       $attributeIds=AttributeClassify::where('classify_id',$classify->id)->pluck('attribute_id');
      return $attrIds=Attribute::whereIn('id',$attributeIds)->get();
    }
}
